package com.gaga.crm.service;

import com.gaga.crm.mapper.SysUserMapper;
import com.gaga.crm.pojo.SysRole;
import com.gaga.crm.pojo.SysUser;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Resource
    private SysUserMapper sysUserMapper;


    @Override
    public SysUser login(String usrName, String usrPassword) {
        List<SysUser> list=sysUserMapper.findByUsrNameAndUsrPassword(usrName,usrPassword);
        if (list.size()==1){
            SysUser user=list.get(0);
            return user;
        }
        return null;
    }

    @Override
    public void saveUser(SysUser user) {
        sysUserMapper.save(user);
    }

    @Override
    public void deleteUser(Long usrId) {
        sysUserMapper.deleteById(usrId);
    }

    @Override
    @Cacheable(value = "user", keyGenerator = "keyGenerator")
    public SysUser getUser(Long usrId) {
        SysUser user=sysUserMapper.findById(usrId).get();
        return user;
    }

    @Override
    public Page<SysUser> findUsers(String usrName, Long roleId, Pageable pageable) {
        Specification<SysUser> specification = new Specification<SysUser>() {
            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (usrName != null && !usrName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("usrName"), "%" + usrName + "%"));
                }
                if (roleId != null && roleId.longValue() != 0l) {
                    SysRole role = new SysRole();
                    role.setRoleId(roleId);
                    predicates.add(criteriaBuilder.equal(root.get("role"), role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return sysUserMapper.findAll(specification, pageable);
    }

    @Override
    public SysUser getUserByUsrName(String usrName) {
        return sysUserMapper.findUserByUsrName(usrName);
    }

    @Override
    public String encryptPassword(Object plaintextPassword) throws IllegalArgumentException{
        String salt = "gaga";
        Md5Hash md5Hash = new Md5Hash(plaintextPassword, salt,2);
        return md5Hash.toString();
    }
}
